package cn.wokoba.service.trade.service.setlement.factory;

import cn.wokoba.service.trade.model.entity.GroupBuyTeamEntity;
import cn.wokoba.service.trade.model.entity.MarketPayOrderEntity;
import cn.wokoba.service.trade.model.entity.TradeSettlementRuleCommandEntity;
import cn.wokoba.service.trade.model.entity.TradeSettlementRuleFilterBackEntity;
import cn.wokoba.service.trade.service.setlement.filter.EndRuleFilter;
import cn.wokoba.service.trade.service.setlement.filter.OutTradeNoRuleFilter;
import cn.wokoba.service.trade.service.setlement.filter.SCRuleFilter;
import cn.wokoba.service.trade.service.setlement.filter.SettableRuleFilter;
import cn.wokoba.types.desgin.framework.link.ILogicLink;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class TradeSettlementRuleFilterFactory {
    private final ILogicLink<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> logicLink;

    public TradeSettlementRuleFilterFactory(List<ILogicLink<TradeSettlementRuleCommandEntity, DynamicContext, TradeSettlementRuleFilterBackEntity>> logicLinkList) {
        logicLinkList.sort(Comparator.comparingInt(this::getOrder));
        for (int i = 0; i < logicLinkList.size() - 1; i++) {
            logicLinkList.get(i).appendNext(logicLinkList.get(i + 1)); // 连接链路
        }
        this.logicLink = logicLinkList.get(0);
    }

    public TradeSettlementRuleFilterBackEntity openLogicLink(String source, String channel, String userId, String outTradeNo, Date outTradeTime) throws Exception {
        return logicLink.apply(TradeSettlementRuleCommandEntity.builder()
                        .source(source)
                        .channel(channel)
                        .userId(userId)
                        .outTradeNo(outTradeNo)
                        .outTradeTime(outTradeTime)
                        .build(),
                new TradeSettlementRuleFilterFactory.DynamicContext());
    }


    private int getOrder(ILogicLink<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> link) {
        if (link instanceof SCRuleFilter) return 1;
        if (link instanceof OutTradeNoRuleFilter) return 2;
        if (link instanceof SettableRuleFilter) return 3;
        if (link instanceof EndRuleFilter) return 4;
        return Integer.MAX_VALUE;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class DynamicContext {
        // 订单营销实体对象
        private MarketPayOrderEntity marketPayOrderEntity;
        // 拼团组队实体对象
        private GroupBuyTeamEntity groupBuyTeamEntity;
    }
}
